package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoaderBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@Slf4j
@RestController
public class OrderController {

    public static final String PAYMENT_URL ="http://CLOUD-PAYMENT-SERVICE/";

    //引入我们自己手写的轮询算法
    @Autowired
    private LoaderBalancer loaderBalancer;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired(required = false)//ByTye
    @Qualifier(value = "getRestTemplate")
    private RestTemplate restTemplate;


    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){

        System.out.println("consumer接收到的参数"+payment.toString());

        return restTemplate.postForObject(PAYMENT_URL+"/payment/create", payment , CommonResult.class);
    }




    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id")Long id)
    {
        log.info("查询操作开始,接受到的id参数是{}",id);
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }


    @GetMapping("/consumer/payment/lb")
    public String paymentLB(){

                                        //获取CLOUD-PAYMENT-SERVICE这个微服务的所有服务提供者
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instanceList == null || instanceList.size()<0) {
            return "你这微服务没有提供者奥";
        }

        ServiceInstance instance = loaderBalancer.instances(instanceList);//返回一个具体的微服务提供者
        URI uri = instance.getUri();//服务提供者的URI

       return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }




    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin(){

        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instanceList == null || instanceList.size()<0) {
            return "你这微服务没有提供者奥";
        }

        ServiceInstance instance = loaderBalancer.instances(instanceList);//返回一个具体的微服务提供者
        URI uri = instance.getUri();//服务提供者的URI

        return restTemplate.getForObject(uri+"/payment/zipkin",String.class);
    }





}
